package pers.cz.javacvdemo.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * SpringContext description
 *
 * @author 
 * @version 1.0.0
 * @date 2023-08-02 11:48:58
 */
@Component
public class SpringContext implements ApplicationContextAware {

	private static ApplicationContext AC;

	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringContext.AC = applicationContext;
	}

	public static <T> T getBean(Class<T> cls) {
		try {
			return AC.getBean(cls);
		} catch (Exception e) {
			return null;
		}
	}

	public static Object getBean(String name) {
		try {
			return AC.getBean(name);
		} catch (Exception e) {
			return null;
		}
	}

	public static <T> T getBean(String name, Class<T> cls) {

		try {
			return AC.getBean(name, cls);
		} catch (Exception e) {
			return null;
		}
	}

	public static <T> Map<String, T> getBeansOfType(Class<T> cls) throws BeansException {
		try {
			return AC.getBeansOfType(cls);
		} catch (Exception e) {
			return null;
		}
	}

	public static <T> String[] getBeanNamesForType(Class<T> cls) throws BeansException {
		try {
			return AC.getBeanNamesForType(cls);
		} catch (Exception e) {
			return null;
		}
	}


	public static String getProperty(String key) {
		try {
			return AC.getEnvironment().getProperty(key);
		} catch (Exception e) {
			return null;
		}
	}

	public static String getProperty(String key, String def) {
		try {
			return AC.getEnvironment().getProperty(key, def);
		} catch (Exception e) {
			return def;
		}
	}

	public static <T> T getProperty(String key, Class<T> cls) {
		try {
			return AC.getEnvironment().getProperty(key, cls);
		} catch (Exception e) {
			return null;
		}
	}

	public static <T> T getProperty(String property, Class<T> cls, T def) {
		try {
			return AC.getEnvironment().getProperty(property, cls, def);
		} catch (Exception e) {
			return def;
		}
	}

	public static String[] getActiveProfiles() {
		return AC.getEnvironment().getActiveProfiles();
	}

}
